﻿using System;
using System.IO;
using System.Data;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Telerik.Web.UI.GridExcelBuilder;
using System.Net.Mail;
using System.Net.Configuration;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;

namespace LenderClearingHouse
{
  public class UserControlBase : UserControl
  {
    protected User CurrentUser
    {
      get { return Session["User"] as User; }
    }
  }

  public abstract class PageBase : Page
  {
    protected User CurrentUser
    {
      get { return Session["User"] as User; }
    }

    protected override void OnInit(EventArgs e)
    {
      if (CurrentUser == null) Response.Redirect("~/Login.aspx");

      base.OnInit(e);
    }
  }

  public enum SourcePage
  {
    MasterList,  
    WorkingList,
    Archive,
    LvreoList,
    LvreoMasterEdit,
    SdreoList,
    EscrowList,
    RehabList,
    GlobalGrid,
    RentProjection
  }

  public abstract class GridPage : PageBase
  {
      RadGrid grid = new RadGrid();

      protected abstract SourcePage GetSourcePage();

      protected override void OnLoad(EventArgs e)
      {
          base.OnLoad(e);

          if (!IsPostBack)
          {
              SaveSortedPropertyIdsToSession(null);
          }

          if (Session[PropertyDetails.STR_WE_ARE_ON_DETAILS] != null)
          {
              Session[PropertyDetails.STR_WE_ARE_ON_DETAILS] = null;
              object sortInfo = Session[GetLastSortingKey()];
              object pageInfo = Session[GetLastPagingKey()];

              if (sortInfo != null)
              {
                  string sortField = (sortInfo as string).Split(';')[0];
                  string sortOrder = (sortInfo as string).Split(';')[1];

                  grid.MasterTableView.SortExpressions.AddSortExpression(
                    new GridSortExpression()
                    {
                        FieldName = sortField,
                        SortOrder = sortOrder == "Ascending" ? GridSortOrder.Ascending : GridSortOrder.Descending
                    });
              }

              if (pageInfo != null)
              {
                  grid.CurrentPageIndex = (int)pageInfo;
              }
          }

          Response.CacheControl = "no-cache";
          Response.AddHeader("Pragma", "no-cache");
          Response.Expires = -1;
          Response.AddHeader("Cache-Control", "no-cache");
          Response.Cache.SetCacheability(HttpCacheability.NoCache);
          Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
          Response.Cache.SetNoStore();
      }

      string GridPageSizeSessionKey { get { return "GridPageSize_" + this.GetType().Name; } }

      void grid_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
      {
          Session[GridPageSizeSessionKey] = e.NewPageSize.ToString();
      }

      protected override void OnInit(EventArgs e)
      {
          base.OnInit(e);

          Session["SourcePage"] = GetSourcePage();

          grid.ID = "grid";
          grid.ShowStatusBar = true;
          grid.AutoGenerateColumns = false;
          grid.AllowSorting = true;
          grid.AllowPaging = true;
          grid.AllowFilteringByColumn = true;
          grid.GroupingSettings.CaseSensitive = false;
          grid.MasterTableView.Width = Unit.Percentage(100);
          grid.MasterTableView.DataKeyNames = new string[] { "PropertyId" };
          grid.MasterTableView.EditFormSettings.ColumnNumber = 4;
          grid.MasterTableView.EditFormSettings.EditColumn.ButtonType = GridButtonColumnType.PushButton;
          grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.None;
          grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
          grid.Width = Unit.Pixel(1160);
          //grid.Height = Unit.Pixel(500);

          grid.ClientSettings.AllowColumnsReorder = true;
          grid.ClientSettings.ReorderColumnsOnClient = true;
          grid.ClientSettings.Scrolling.AllowScroll = true;
          grid.ClientSettings.Scrolling.UseStaticHeaders = true;
          grid.ClientSettings.Scrolling.SaveScrollPosition = true;
          grid.ClientSettings.Scrolling.ScrollHeight = Unit.Pixel(500);
          grid.SortCommand += new GridSortCommandEventHandler(grid_SortCommand);
          grid.PageIndexChanged += new GridPageChangedEventHandler(grid_PageIndexChanged);
          grid.PageSizeChanged += new GridPageSizeChangedEventHandler(grid_PageSizeChanged);
          grid.PreRender += new EventHandler(grid_PreRender);

          grid.ExportSettings.ExportOnlyData = true;
          grid.ExportSettings.IgnorePaging = true;
          grid.ExportSettings.OpenInNewWindow = true;
          grid.ExportSettings.Excel.Format = GridExcelExportFormat.ExcelML;
          grid.ExcelMLExportStylesCreated += new Telerik.Web.UI.GridExcelBuilder.GridExcelMLExportStylesCreatedEventHandler(grid_ExcelMLExportStylesCreated);
          grid.ExcelMLExportRowCreated += new GridExcelMLExportRowCreatedEventHandler(grid_ExcelMLExportRowCreated);

          grid.DataSourceID = GetDataSourceID();
          CreateColumns(grid.Columns);

          //
          // frozen address functionality
          //
          for (int i = 0; i < grid.Columns.Count; i++)
          {
              grid.Columns[i].Reorderable = false;

              if (grid.Columns[i].UniqueName == "Address")
              {
                  grid.ClientSettings.Scrolling.FrozenColumnsCount = i + 1;
                  break;
              }
          }

          GetGridContainer().Controls.Add(grid);

          SetupSqlDataSource(GetSqlDataSource());

          grid.PagerStyle.AlwaysVisible = true;
          try
          {
              grid.PageSize = int.Parse(Session[GridPageSizeSessionKey].ToString());
          }
          catch
          {
              grid.PageSize = 20;
          }
          grid.ItemDataBound += new GridItemEventHandler(grid_ItemDataBound);
          grid.ItemCreated +=new GridItemEventHandler(grid_ItemCreated);
      }

      void grid_PreRender(object sender, EventArgs e)
      {
      }

      void grid_PageIndexChanged(object sender, GridPageChangedEventArgs e)
      {
          Session[GetLastPagingKey()] = e.NewPageIndex;
      }

      const string STR_LAST_SORTING = "last_sorting_{0}";
      const string STR_LAST_PAGING = "last_paging_{0}";

      string GetLastSortingKey()
      {
          return string.Format(STR_LAST_SORTING, GetSourcePage().ToString());
      }

      string GetLastPagingKey()
      {
          return string.Format(STR_LAST_PAGING, GetSourcePage().ToString());
      }

      void grid_SortCommand(object sender, GridSortCommandEventArgs e)
      {
          string lastSortingKey = GetLastSortingKey();
          Session[lastSortingKey] = e.SortExpression + ";" + e.NewSortOrder.ToString();

          SaveSortedPropertyIdsToSession(e.SortExpression + " "
              + (e.NewSortOrder.ToString().StartsWith("Asc") ? "ASC" : "DESC"));
      }

      /// <summary>
      /// это нужно чтобы при просмотре property details отображать ссылки "next", "previous"
      /// для навигации по пропертям
      /// </summary>
      /// <param name="sortExpression"></param>
      void SaveSortedPropertyIdsToSession(string sortExpression)
      {
          if (ForceEdit)
              return;

          DataTable tbl = (GetSqlDataSource().Select(DataSourceSelectArguments.Empty) as DataView).Table;
          List<int> ids = new List<int>();

          if (string.IsNullOrEmpty(sortExpression))
          {
              foreach (DataRow dr in tbl.Rows)
              {
                  ids.Add(Convert.ToInt32(dr["PropertyId"]));
              }
          }
          else
          {
              foreach (DataRow dr in tbl.Select("", sortExpression))
              {
                  ids.Add(Convert.ToInt32(dr["PropertyId"]));
              }
          }

          Session["AllPropertiesIds"] = ids.ToArray();
      }

      protected virtual void grid_ItemDataBound(object sender, GridItemEventArgs e)
      {
          if (e.Item is GridPagerItem)
          {
              GridPagerItem item = e.Item as GridPagerItem;
              RadComboBox combo = (RadComboBox)item.FindControl("PageSizeComboBox");

              RadComboBoxItem newItem = combo.Items.FindItemByValue("100");
              if (newItem == null)
              {
                  RadComboBoxItem citem = new RadComboBoxItem("100", "100");
                  citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                  combo.Items.Add(citem);
              }
              else
              {
                  newItem.Text = "100";
              }

              newItem = combo.Items.FindItemByValue("1000000");
              if (newItem == null)
              {
                  RadComboBoxItem citem = new RadComboBoxItem("ALL", "1000000");
                  citem.Attributes.Add("ownerTableViewId", e.Item.OwnerTableView.ClientID);
                  combo.Items.Add(citem);

                  if (grid.PageSize == 1000000)
                  {
                      combo.SelectedValue = "1000000";
                  }
              }
              else
              {
                  newItem.Text = "ALL";
              }

              //combo.SelectedIndex = 0;
          }
          else if (e.Item is GridDataItem)
          {
              GridDataItem itm = e.Item as GridDataItem;
              DataRowView drw = itm.DataItem as DataRowView;
              if (drw["CloseDate"] != DBNull.Value/* && drw["CloseDate"].ToString() != ""*/)
              {
                  itm.BackColor = System.Drawing.Color.FromArgb(204, 153, 255);
              }
          }
      }

      protected virtual void grid_ItemCreated(object sender, GridItemEventArgs e)
      {
          if (!Page.IsPostBack && e.Item is GridEditableItem && ForceEdit)
          {
              e.Item.Edit = true;
          }
      }

      void grid_ExcelMLExportRowCreated(object sender, GridExportExcelMLRowCreatedArgs e)
      {
          foreach (CellElement ce in e.Row.Cells)
          {
              ce.StyleValue = "MyCustomStyle";
          }
      }

      void grid_ExcelMLExportStylesCreated(object sender, Telerik.Web.UI.GridExcelBuilder.GridExportExcelMLStyleCreatedArgs e)
      {
          StyleElement cstyle = new StyleElement("MyCustomStyle");
          BorderStylesCollection borders = new BorderStylesCollection();
          BorderStyles borderStyle;
          for (int i = 1; i <= 4; i++) //four borders   
          {
              borderStyle = new BorderStyles();
              borderStyle.PositionType = (PositionType)i;
              borderStyle.Color = System.Drawing.Color.Black;
              borderStyle.LineStyle = LineStyle.Continuous;
              borderStyle.Weight = 1.0;
              borders.Add(borderStyle);
          }
          foreach (BorderStyles border in borders)
              cstyle.Borders.Add(border);
          e.Styles.Add(cstyle);
      }

      protected virtual void SetupSqlDataSource(SqlDataSource dataSource)
      {
          dataSource.SelectParameters.Add(new Parameter()
          {
              ConvertEmptyStringToNull = false,
              Name = "Apn",
              Type = TypeCode.String
          });
          dataSource.SelectParameters.Add(new Parameter()
          {
              ConvertEmptyStringToNull = false,
              Name = "PropLocation",
              Type = TypeCode.String
          });
          dataSource.SelectParameters.Add(new Parameter()
          {
              ConvertEmptyStringToNull = false,
              Name = "Zip",
              Type = TypeCode.String
          });

          dataSource.Selecting += new SqlDataSourceSelectingEventHandler(dataSource_Selecting);
          dataSource.Selected += new SqlDataSourceStatusEventHandler(dataSource_Selected);
      }

      void dataSource_Selected(object sender, SqlDataSourceStatusEventArgs e)
      {

      }

      void dataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
      {
          ListFilterControl listFilter = GetListFilterControl();

          if (listFilter != null)
          {
              e.Command.Parameters["@Apn"].Value = listFilter.Apn;
              e.Command.Parameters["@PropLocation"].Value = listFilter.Address;
              e.Command.Parameters["@Zip"].Value = listFilter.Zip;
          }
          else
          {
              e.Command.Parameters["@Apn"].Value = "";
              e.Command.Parameters["@PropLocation"].Value = "";
              e.Command.Parameters["@Zip"].Value = "";
          }

          if (!string.IsNullOrEmpty(Apn))
              e.Command.Parameters["@Apn"].Value = Apn;
      }

      protected abstract SqlDataSource GetSqlDataSource();
      protected abstract ListFilterControl GetListFilterControl();
      protected abstract Control GetGridContainer();
      protected abstract string GetDataSourceID();

      protected RadGrid Grid
      {
          get { return GetGridContainer().Controls[0] as RadGrid; }
      }

      public const int INT_COMMON_WIDTH = 100;

      protected void HideColumn(string uniqueName)
      {
          GridColumn col = Grid.MasterTableView.Columns.FindByUniqueNameSafe(uniqueName);
          if (col != null) col.Visible = false;
      }

      protected virtual void CreateColumns(GridColumnCollection columns)
      {
          GridBoundColumn col;
          GridTemplateColumn gtc;

          /*col = new GridBoundColumn();
          col.DataField = "PropertyLocation";
          col.HeaderText = "Address";
          col.UniqueName = "Address";
          col.ConvertEmptyStringToNull = false;
          col.ReadOnly = true;
          col.Display = true;
          col.HeaderStyle.Width = Unit.Pixel(150);
          columns.Add(col);*/

          GridHyperLinkColumn hlc = new GridHyperLinkColumn()
          {
              HeaderText = "Address",
              DataNavigateUrlFormatString = "~/PropertyDetails2.aspx?propertyId={0}",
              DataNavigateUrlFields = new string[] { "PropertyId" },
              EditFormColumnIndex = 0,
              DataTextField = "PropertyLocation",
              UniqueName = "Address",
              SortExpression = "PropertyLocation"
          };
          hlc.HeaderStyle.Width = Unit.Pixel(150);
          columns.Add(hlc);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "ListingStatus",
              HeaderText = "Status",
              ItemTemplate = new SpanColumn("ListingStatus"),
              EditItemTemplate = new StatusColumnEdit("ListingStatus"),
              EditFormColumnIndex = 0,
              SortExpression = "ListingStatus",
              DataField = "ListingStatus"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          if (GetSourcePage() == SourcePage.MasterList)
          {
              col = new GridBoundColumn();
              col.DataField = "Client";
              col.HeaderText = "Client";
              col.ConvertEmptyStringToNull = false;
              col.EditFormColumnIndex = 0;
              col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
              col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
              columns.Add(col);
          }

          // 36
          columns.Add(Utilities.CreateTemlateDateColumn("CloseDate", "Close Date", 2));

          // 42
          col = new GridBoundColumn();
          col.DataField = "Source";
          col.HeaderText = "Source";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 31
          columns.Add(Utilities.CreateTemlateDateColumn("DateRecorded", "Date of Reservation", 2));

          // 37
          col = new GridBoundColumn();
          col.DataField = "EscrowCompany";
          col.HeaderText = "Company";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "Apn",
              HeaderText = "Apn",
              ItemTemplate = new SpanColumn("Apn"),
              EditItemTemplate = new RequiredColumnEdit("Apn"),
              EditFormColumnIndex = 0,
              SortExpression = "Apn",
              DataField = "Apn"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 5
          //GridHyperLinkColumn hlc = new GridHyperLinkColumn()
          //{
          //  HeaderText = "PropertyLocation",
          //  DataNavigateUrlFormatString = "~/PropertyDetails.aspx?propertyId={0}",
          //  DataNavigateUrlFields = new string[] { "PropertyId" },
          //  EditFormColumnIndex = 0,
          //  DataTextField = "PropertyLocation",
          //  SortExpression = "PropertyLocation"
          //};
          //hlc.HeaderStyle.Width = Unit.Pixel(150);
          //columns.Add(hlc);

          // 5
          col = new GridBoundColumn();
          col.DataField = "PropertyLocation";
          col.HeaderText = "PropertyLocation";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 0;
          col.Display = false;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 6
          col = new GridBoundColumn();
          col.DataField = "ZipCode";
          col.HeaderText = "ZipCode";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 0;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 33
          col = new GridBoundColumn();
          col.DataField = "AssessorDesc";
          col.HeaderText = "AssessorDesc";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH * 3);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH * 3 - 40);
          columns.Add(col);

          // 8
          gtc = new GridTemplateColumn()
          {
              UniqueName = "HOA",
              HeaderText = "HOA",
              ItemTemplate = new DollarColumn("HOA"),
              EditItemTemplate = new CurrencyColumnEdit("HOA"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 0,
              DataField = "HOA",
              SortExpression = "HOA"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 9
          col = new GridBoundColumn();
          col.DataField = "Stories";
          col.HeaderText = "Stories";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 0;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 10
          col = new GridBoundColumn();
          col.DataField = "ConstructYear";
          col.HeaderText = "ConstYear";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 1;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 11
          col = new GridBoundColumn();
          col.DataField = "TotalSqft";
          col.HeaderText = "TotalSqft";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 1;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 12
          col = new GridBoundColumn();
          col.DataField = "LotSize";
          col.HeaderText = "LotSize";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 1;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 13
          gtc = new GridTemplateColumn()
          {
              UniqueName = "Bedrooms",
              HeaderText = "Bed",
              ItemTemplate = new SpanColumn("Bedrooms"),
              EditItemTemplate = new RoomsColumnEdit("Bedrooms"),
              EditFormColumnIndex = 1,
              DataField = "Bedrooms",
              SortExpression = "Bedrooms"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 14
          col = new GridBoundColumn();
          col.DataField = "Bathrooms";
          col.HeaderText = "Bath";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 1;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 15
          col = new GridBoundColumn();
          col.DataField = "GarageSqft";
          col.HeaderText = "GarageSqft";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 1;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          // 16
          gtc = new GridTemplateColumn()
          {
              UniqueName = "Pool",
              HeaderText = "Pool",
              ItemTemplate = new SpanColumn("Pool"),
              EditItemTemplate = new YesNoColumnEdit("Pool"),
              EditFormColumnIndex = 1,
              DataField = "Pool",
              SortExpression = "Pool"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 17
          gtc = new GridTemplateColumn()
          {
              UniqueName = "Spa",
              HeaderText = "Spa",
              ItemTemplate = new SpanColumn("Spa"),
              EditItemTemplate = new YesNoColumnEdit("Spa"),
              EditFormColumnIndex = 2,
              DataField = "Spa",
              SortExpression = "Spa"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 39
          col = new GridBoundColumn();
          col.DataField = "PrelistStatus";
          col.HeaderText = "Prelist Status";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "PurchasePrice",
              HeaderText = "Purchase Price",
              ItemTemplate = new DollarColumn("PurchasePrice"),
              EditItemTemplate = new CurrencyColumnEdit("PurchasePrice"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 2,
              DataField = "PurchasePrice",
              SortExpression = "PurchasePrice"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 41
          gtc = new GridTemplateColumn()
          {
              UniqueName = "RehabCosts",
              HeaderText = "Rehab Costs",
              ItemTemplate = new DollarColumn("RehabCosts"),
              EditItemTemplate = new CurrencyColumnEdit("RehabCosts"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 2,
              DataField = "RehabCosts",
              SortExpression = "RehabCosts"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          // 38
          col = new GridBoundColumn();
          col.DataField = "MiscNotes";
          col.HeaderText = "Misc Notes";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(400);
          col.FilterControlWidth = Unit.Pixel(360);
          columns.Add(col);

          // 32
          col = new GridBoundColumn();
          col.DataField = "LandUse";
          col.HeaderText = "LandUse";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH * 2);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH * 2 - 40);
          columns.Add(col);

          // 34
          gtc = new GridTemplateColumn()
          {
              UniqueName = "Phase",
              HeaderText = "Phase",
              ItemTemplate = new SpanColumn("Phase"),
              EditItemTemplate = new PhaseColumnEdit("Phase"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 2,
              DataField = "Phase",
              SortExpression = "Phase"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          if (GetSourcePage() == SourcePage.LvreoList || GetSourcePage() == SourcePage.SdreoList) return;


          /*if (GetSourcePage() != SourcePage.MasterList)
          {
              columns.Add(Utilities.CreateTemlateDateColumn("AuctionDate", "Auction Date", 1));
          }
          else
          {
              col = new GridBoundColumn();
              col.DataField = "AuctionDate";
              col.HeaderText = "Auction Date";
              col.ConvertEmptyStringToNull = false;
              col.EditFormColumnIndex = 1;
              col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
              col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
              columns.Add(col);
          }*/
          columns.Add(Utilities.CreateTemlateDateColumn("AuctionDate", "Auction Date", 1));

          col = new GridBoundColumn();
          col.DataField = "Trustee";
          col.HeaderText = "Trustee";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          col = new GridBoundColumn();
          col.DataField = "TsNumber";
          col.HeaderText = "Ts Number";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 0;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "EstimatedBid",
              HeaderText = "Estimated Bid",
              ItemTemplate = new DollarColumn("EstimatedBid"),
              EditItemTemplate = new CurrencyColumnEdit("EstimatedBid"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 1,
              DataField = "EstimatedBid",
              SortExpression = "EstimatedBid"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "TsOpeningBid",
              HeaderText = "Opening Bid",
              ItemTemplate = new DollarColumn("TsOpeningBid"),
              EditItemTemplate = new CurrencyColumnEdit("TsOpeningBid"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 0,
              DataField = "TsOpeningBid",
              SortExpression = "TsOpeningBid"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);

          col = new GridBoundColumn();
          col.DataField = "Nos";
          col.HeaderText = "NOS";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 0;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          col = new GridBoundColumn();
          col.DataField = "Liens";
          col.HeaderText = "Liens";
          col.ConvertEmptyStringToNull = false;
          col.EditFormColumnIndex = 2;
          col.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          col.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(col);

          gtc = new GridTemplateColumn()
          {
              UniqueName = "Tax",
              HeaderText = "Taxes Due",
              ItemTemplate = new DollarColumn("Tax"),
              EditItemTemplate = new CurrencyColumnEdit("Tax"),
              ConvertEmptyStringToNull = false,
              EditFormColumnIndex = 1,
              DataField = "Tax",
              SortExpression = "Tax"
          };
          gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
          gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
          columns.Add(gtc);
      }

      protected string Apn
      {
          get
          {
              string result = "";
              if (Request.QueryString["apn"] != null)
                  result = Request.QueryString["apn"].ToString();

              return result;
          }
      }

      protected bool ForceEdit
      {
          get
          {
              return (Request.QueryString["edit"] != null);
          }
      }
  }

  public abstract class EditablePage : GridPage
  {
      protected abstract string GetPropertyDetailsColumnEditorID();

      protected override void OnInit(EventArgs e)
      {
          base.OnInit(e);

          (Grid.Columns.FindByDataField("MiscNotes") as GridBoundColumn).ColumnEditorID =
            GetPropertyDetailsColumnEditorID();

          if (IsEditable())
          {
              Grid.AllowAutomaticDeletes = true;
              Grid.AllowAutomaticInserts = true;
              Grid.AllowAutomaticUpdates = true;
              Grid.MasterTableView.CommandItemDisplay = AllowInsert ? GridCommandItemDisplay.Top : GridCommandItemDisplay.None;
          }
      }

      protected virtual string GetDateTimeColumnEditorID()
      {
          return "";
      }

      protected override void SetupSqlDataSource(SqlDataSource dataSource)
      {
          base.SetupSqlDataSource(dataSource);

          if (!IsEditable()) return;

          if (AllowInsert)
          {
              SetupParameters(dataSource.InsertParameters);
          }

          dataSource.UpdateParameters.Add(new Parameter("PropertyId", TypeCode.Int32)
          {
              ConvertEmptyStringToNull = false
          });
          SetupParameters(dataSource.UpdateParameters);

          if (AllowDelete)
          {
              dataSource.DeleteParameters.Add(new Parameter("PropertyId", TypeCode.Int32)
              {
                  ConvertEmptyStringToNull = false
              });
          }
      }

      protected virtual void SetupParameters(ParameterCollection coll)
      {
          //coll.Add(new Parameter("OnOff"));
          coll.Add(new Parameter("Trustee"));
          coll.Add(new Parameter("TsNumber"));
          coll.Add(new Parameter("Apn"));
          coll.Add(new Parameter("PropertyLocation"));
          coll.Add(new Parameter("ZipCode"));
          //coll.Add(new Parameter("VO"));
          coll.Add(new Parameter("HOA"));
          coll.Add(new Parameter("Stories"));
          coll.Add(new Parameter("ConstructYear"));
          coll.Add(new Parameter("TotalSQft"));
          coll.Add(new Parameter("LotSize"));
          coll.Add(new Parameter("Bedrooms"));
          coll.Add(new Parameter("Bathrooms"));
          coll.Add(new Parameter("GarageSqft"));
          coll.Add(new Parameter("Pool"));
          coll.Add(new Parameter("Spa"));
          coll.Add(new Parameter("AuctionDate"));
          //coll.Add(new Parameter("ListingStatus"));
          coll.Add(new Parameter("EstimatedBid"));
          coll.Add(new Parameter("TsOpeningBid"));
          //coll.Add(new Parameter("ApnOpeningBid"));
          //coll.Add(new Parameter("MaxBid"));
          //coll.Add(new Parameter("EstVal"));
          coll.Add(new Parameter("Tax"));
          coll.Add(new Parameter("Nos"));
          coll.Add(new Parameter("Liens"));
          //coll.Add(new Parameter("Site"));
          //coll.Add(new Parameter("PropertyDetails"));
          //coll.Add(new Parameter("DocumentNumber"));
          coll.Add(new Parameter("DateRecorded"));
          coll.Add(new Parameter("LandUse"));
          coll.Add(new Parameter("AssessorDesc"));
          coll.Add(new Parameter("Phase"));
          coll.Add(new Parameter("Client"));
          coll.Add(new Parameter("CloseDate"));
          coll.Add(new Parameter("EscrowCompany"));
          coll.Add(new Parameter("MiscNotes"));
          coll.Add(new Parameter("PrelistStatus"));
          coll.Add(new Parameter("PurchasePrice"));
          coll.Add(new Parameter("RehabCosts"));
          coll.Add(new Parameter("Source"));

          foreach (Parameter p in coll)
          {
              p.Type = TypeCode.String;
              p.ConvertEmptyStringToNull = false;
          }
      }

      protected virtual bool AllowInsert
      {
          get { return true; }
      }

      protected virtual bool AllowDelete
      {
          get { return true; }
      }

      protected override void CreateColumns(GridColumnCollection columns)
      {
          if (IsEditable())
          {
              if (AllowDelete)
              {
                  GridButtonColumn gbc = new GridButtonColumn()
                  {
                      ConfirmText = "Delete this property?",
                      ConfirmDialogType = GridConfirmDialogType.Classic,
                      ConfirmTitle = "Delete",
                      ButtonType = GridButtonColumnType.ImageButton,
                      CommandName = "Delete",
                      Text = "Delete",
                      UniqueName = "DeleteButton"
                  };
                  gbc.HeaderStyle.Width = Unit.Pixel(30);
                  columns.Add(gbc);
              }

              GridEditCommandColumn ecc = new GridEditCommandColumn()
              {
                  ButtonType = GridButtonColumnType.ImageButton,
                  UniqueName = "EditButton"
              };
              ecc.HeaderStyle.Width = Unit.Pixel(30);
              columns.Add(ecc);
          }

          base.CreateColumns(columns);
      }

      protected abstract bool IsEditable();
  }

  public abstract class InvestorAdminPage : EditablePage
  {
    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);

      Grid.ItemDataBound += new GridItemEventHandler(Grid_ItemDataBound);
      Grid.ItemEvent += new GridItemEventHandler(Grid_ItemEvent);
      GetSqlDataSource().Updated += new SqlDataSourceStatusEventHandler(InvestorAdminPage_Updated);
      GetSqlDataSource().Inserted += new SqlDataSourceStatusEventHandler(InvestorAdminPage_Updated);
    }

    void Grid_ItemEvent(object sender, GridItemEventArgs e)
    {
      if (e.Item is GridEditFormItem)
      {
        if (!((e.Item as GridEditFormItem).DataItem is DataRowView)) return;

        DataRowView drw = (DataRowView)(e.Item as GridEditFormItem).DataItem;
        if (drw == null) return;

        if (drw["InvestorId"] != DBNull.Value)
        {
          Session["LastInvestorId"] = drw["InvestorId"].ToString();
        }
        else Session["LastInvestorId"] = "";
      }
    }

    void InvestorAdminPage_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
      string investorId = e.Command.Parameters["@InvestorName"].Value.ToString();
      if (investorId == "") return;
      if (Session["LastInvestorId"] != null
        && Session["LastInvestorId"].ToString() == investorId) return;

      DataAccess da = new DataAccess();
      DataTable tbl = da.ExecuteSQL("select * from UserAccounts where UserId = " + investorId);

      try
      {
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;

        System.Configuration.Configuration config =
          WebConfigurationManager.OpenWebConfiguration("~/");
        SmtpSection smtpSection = (SmtpSection)config.GetSection("system.net/mailSettings/smtp");

        MailMessage msg = new MailMessage();
        msg.From = new MailAddress(smtpSection.Network.UserName);

        msg.To.Add(tbl.Rows[0]["Email"].ToString());
        msg.Subject = "property " + e.Command.Parameters["@Apn"].Value.ToString() + " assigned";
        msg.IsBodyHtml = true;
        msg.Body = File.ReadAllText(Server.MapPath("~/Template/PropertyAssigned.htm"));
        msg.Body = msg.Body.Replace("%InvestorName%",
          tbl.Rows[0]["FName"].ToString() + " " + tbl.Rows[0]["LName"].ToString()).Replace(
          "%PropertyAddress%",
          e.Command.Parameters["@PropertyLocation"].Value.ToString());

        client.Send(msg);


        ScriptManager.RegisterStartupScript(this, this.GetType(), "key",
          "alert('Email to investor has been sent successfully');", true);
      }
      catch (Exception ex)
      {
        ScriptManager.RegisterStartupScript(this, this.GetType(),
            "key", "alert('Error: " + ex.Message + "');", true);
      }
    }

    protected virtual void Grid_ItemDataBound(object sender, GridItemEventArgs e)
    {
      if (!(e.Item is GridDataItem)) return;

      GridDataItem itm = e.Item as GridDataItem;
      DataRowView drw = itm.DataItem as DataRowView;

      if (drw["CloseDate"] != DBNull.Value
        && drw["CloseDate"].ToString() != "") return;

      if (drw["InvestorName"] != DBNull.Value && drw["InvestorName"].ToString() != "")
      {
        itm.BackColor = System.Drawing.Color.Yellow;
      }
    }

    protected override void SetupSqlDataSource(SqlDataSource dataSource)
    {
      base.SetupSqlDataSource(dataSource);

      dataSource.InsertParameters.Add(new Parameter("investorName")
      {
        ConvertEmptyStringToNull = true
      });

      dataSource.UpdateParameters.Add(new Parameter("investorName")
      {
        ConvertEmptyStringToNull = true
      });

      dataSource.SelectParameters.Add(new Parameter()
      {
        ConvertEmptyStringToNull = false,
        Name = "showAllUnassigned",
        Type = TypeCode.Boolean
      });
    }

    protected override void CreateColumns(GridColumnCollection columns)
    {
      base.CreateColumns(columns);

      GridTemplateColumn gtc = new GridTemplateColumn()
      {
        UniqueName = "InvestorName",
        HeaderText = "Investor",
        ItemTemplate = new SpanColumn("InvestorName"),
        EditItemTemplate = new InvestorColumnEdit("InvestorName", GetSourcePage()),
        ConvertEmptyStringToNull = false,
        EditFormColumnIndex = 0,
        DataField = "InvestorName",
        SortExpression = "InvestorName"
      };
      gtc.HeaderStyle.Width = Unit.Pixel(INT_COMMON_WIDTH);
      gtc.FilterControlWidth = Unit.Pixel(INT_COMMON_WIDTH - 40);
      columns.Insert(3, gtc);
    }
  }

  class YesNoColumnEdit : IBindableTemplate
  {
    string columnName;

    public YesNoColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlYesNo" + columnName;
      ddl.Width = Unit.Pixel(100);
      ddl.Items.AddRange(new ListItem[]
        {
          new ListItem("NO"),
          new ListItem("YES")
        });
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw[columnName].ToString();
      if (ddl.Items.FindByText(val) != null)
      {
        ddl.SelectedValue = val;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlYesNo" + columnName))).SelectedValue);
      return od;
    }
  }

  class CurrencyColumnEdit : IBindableTemplate
  {
      string format;
      string columnName;

    public CurrencyColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public CurrencyColumnEdit(string columnName, string format)
    {
        this.columnName = columnName;
        this.format = format;
    }

    public void InstantiateIn(Control container)
    {
        Label lbl = new Label();
        lbl.Text = "$";
        container.Controls.Add(lbl);

        TextBox ddl = new TextBox();
      ddl.ID = "tb" + columnName;
      ddl.Width = Unit.Pixel(140);
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      TextBox ddl = (TextBox)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

        string val;
        if (string.IsNullOrEmpty(format))
            val = drw[columnName].ToString();
        else
            val = Convert.ToDecimal(drw[columnName]).ToString(format);

      ddl.Text = val;
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((TextBox)(((GridEditFormItem)(container)).FindControl("tb" + columnName))).Text);
      return od;
    }
  }

  class DateColumnEdit : IBindableTemplate
  {
      string columnName;

      public DateColumnEdit(string columnName)
      {
          this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
          TextBox ddl = new TextBox();
          ddl.ID = "tb" + columnName;
          ddl.Width = Unit.Pixel(140);
          ddl.DataBinding += new EventHandler(ddl_DataBinding);

          container.Controls.Add(ddl);
      }

      void ddl_DataBinding(object sender, EventArgs e)
      {
          TextBox ddl = (TextBox)sender;
          GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
          DataRowView drw = container.DataItem as DataRowView;
          if (drw == null) return;

          try
          {
              ddl.Text = ((DateTime)drw[columnName]).ToString("MM/dd/yyyy");
          }
          catch
          {
          }
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
          OrderedDictionary od = new OrderedDictionary();
          od.Add(columnName, ((TextBox)(((GridEditFormItem)(container)).FindControl("tb" + columnName))).Text);
          return od;
      }
  }

  class DateTimeColumnEdit : IBindableTemplate
  {
      string columnName;

      public DateTimeColumnEdit(string columnName)
      {
          this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
          TextBox ddl = new TextBox();
          ddl.ID = "tb" + columnName;
          ddl.Width = Unit.Pixel(140);
          ddl.DataBinding += new EventHandler(ddl_DataBinding);

          container.Controls.Add(ddl);
      }

      void ddl_DataBinding(object sender, EventArgs e)
      {
          TextBox ddl = (TextBox)sender;
          GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
          DataRowView drw = container.DataItem as DataRowView;
          if (drw == null) return;

          try
          {
              ddl.Text = ((DateTime)drw[columnName]).ToString();
          }
          catch
          {
          }
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
          OrderedDictionary od = new OrderedDictionary();
          od.Add(columnName, ((TextBox)(((GridEditFormItem)(container)).FindControl("tb" + columnName))).Text);
          return od;
      }
  }

  class SpanColumn : IBindableTemplate
  {
    string columnName;

    public SpanColumn(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      HtmlGenericControl span = new HtmlGenericControl("div");
      span.DataBinding += new EventHandler(span_DataBinding);

      container.Controls.Add(span);
    }

    void span_DataBinding(object sender, EventArgs e)
    {
      HtmlGenericControl span = (HtmlGenericControl)sender;
      GridDataItem container = (GridDataItem)span.NamingContainer;
      span.InnerText = (container.DataItem as DataRowView)[columnName].ToString();
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      return od;
    }
  }

  class SpanDateColumn : IBindableTemplate
  {
      string columnName;

      public SpanDateColumn(string columnName)
      {
          this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
          HtmlGenericControl span = new HtmlGenericControl("div");
          span.DataBinding += new EventHandler(span_DataBinding);

          container.Controls.Add(span);
      }

      void span_DataBinding(object sender, EventArgs e)
      {
          HtmlGenericControl span = (HtmlGenericControl)sender;
          GridDataItem container = (GridDataItem)span.NamingContainer;
          try
          {
              span.InnerText = ((DateTime)(container.DataItem as DataRowView)[columnName]).ToString("MM/dd/yyyy");
          }
          catch { }
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
          OrderedDictionary od = new OrderedDictionary();
          return od;
      }
  }

  class SpanDateTimeColumn : IBindableTemplate
  {
      string columnName;

      public SpanDateTimeColumn(string columnName)
      {
          this.columnName = columnName;
      }

      public void InstantiateIn(Control container)
      {
          HtmlGenericControl span = new HtmlGenericControl("div");
          span.DataBinding += new EventHandler(span_DataBinding);

          container.Controls.Add(span);
      }

      void span_DataBinding(object sender, EventArgs e)
      {
          HtmlGenericControl span = (HtmlGenericControl)sender;
          GridDataItem container = (GridDataItem)span.NamingContainer;
          try
          {
              span.InnerText = ((DateTime)(container.DataItem as DataRowView)[columnName]).ToString();
          }
          catch { }
      }

      public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
      {
          OrderedDictionary od = new OrderedDictionary();
          return od;
      }
  }

  class DollarColumn : IBindableTemplate
  {
    string columnName;
    string format;

    public DollarColumn(string columnName)
    {
      this.columnName = columnName;
    }

    public DollarColumn(string columnName, string format)
    {
        this.columnName = columnName;
        this.format = format;
    }

    public void InstantiateIn(Control container)
    {
      HtmlGenericControl span = new HtmlGenericControl("span");
      span.DataBinding += new EventHandler(span_DataBinding);

      container.Controls.Add(span);
    }

    void span_DataBinding(object sender, EventArgs e)
    {
      HtmlGenericControl span = (HtmlGenericControl)sender;
      GridDataItem container = (GridDataItem)span.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      if (string.IsNullOrEmpty(format))
          span.InnerText = drw[columnName].ToString();
      else
      {
          decimal outValue = 0;
          if (drw[columnName] == System.DBNull.Value)
              outValue = 0;
          else if (drw[columnName] is string)
          {
              if (!decimal.TryParse(drw[columnName].ToString(), out outValue))
                  outValue = 0;
          }
          else
              outValue = Convert.ToDecimal(drw[columnName]);

          span.InnerText = outValue.ToString(format);
      }

      if (span.InnerText != "") span.InnerText = "$" + span.InnerText;
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      return od;
    }
  }

  class VOColumnEdit : IBindableTemplate
  {
    string columnName;

    public VOColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlVO" + columnName;
      ddl.Width = Unit.Pixel(100);
      ddl.Items.AddRange(new ListItem[]
        {
          new ListItem("V"),
          new ListItem("O")
        });
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw[columnName].ToString();
      if (ddl.Items.FindByText(val) != null)
      {
        ddl.SelectedValue = val;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlVO" + columnName))).SelectedValue);
      return od;
    }
  }

  class RoomsColumnEdit : IBindableTemplate
  {
    string columnName;

    public RoomsColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlRooms" + columnName;
      ddl.Width = Unit.Pixel(100);
      for (int i = 1; i <= 20; i++)
      {
        ddl.Items.Add(i.ToString());
      }
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw[columnName].ToString();
      if (ddl.Items.FindByText(val) != null)
      {
        ddl.SelectedValue = val;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlRooms" + columnName))).SelectedValue);
      return od;
    }
  }

  class PhaseColumnEdit : IBindableTemplate
  {
    string columnName;

    public PhaseColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlPhase" + columnName;
      ddl.Width = Unit.Pixel(100);
      for (int i = 1; i <= 2; i++)
      {
        ddl.Items.Add(i.ToString());
      }
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw[columnName].ToString();
      if (ddl.Items.FindByText(val) != null)
      {
        ddl.SelectedValue = val;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlPhase" + columnName))).SelectedValue);
      return od;
    }
  }

  class StatusColumnEdit : IBindableTemplate
  {
    string columnName;

    public StatusColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlStatus" + columnName;
      ddl.Items.AddRange(new ListItem[]
        {
          new ListItem("Available"),
          new ListItem("Reserved"),
          new ListItem("Unassigned")
        });
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null)
      {
        ddl.SelectedIndex = 2;
        return;
      }

      string val = drw[columnName].ToString();
      if (ddl.Items.FindByText(val) != null)
      {
        ddl.Items.FindByText(val).Selected = true;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlStatus" + columnName))).SelectedItem.Text);
      return od;
    }
  }

  class RequiredColumnEdit : IBindableTemplate
  {
    string columnName;

    public RequiredColumnEdit(string columnName)
    {
      this.columnName = columnName;
    }

    public void InstantiateIn(Control container)
    {
      TextBox ddl = new TextBox();
      ddl.ID = "tb" + columnName;
      ddl.Width = Unit.Pixel(140);
      ddl.DataBinding += new EventHandler(ddl_DataBinding);
      container.Controls.Add(ddl);

      RequiredFieldValidator validator = new RequiredFieldValidator();
      validator.ControlToValidate = ddl.ID;
      validator.ErrorMessage = "Required field";
      validator.SetFocusOnError = true;
      validator.ForeColor = System.Drawing.Color.Red;
      container.Controls.Add(validator);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      TextBox ddl = (TextBox)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw[columnName].ToString();
      ddl.Text = val;
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((TextBox)(((GridEditFormItem)(container)).FindControl("tb" + columnName))).Text);
      return od;
    }
  }

  class InvestorColumnEdit : IBindableTemplate
  {
    string columnName;
    SourcePage sourcePage;

    public InvestorColumnEdit(string columnName, SourcePage sourcePage)
    {
      this.columnName = columnName;
      this.sourcePage = sourcePage;
    }

    public void InstantiateIn(Control container)
    {
      User usr = container.Page.Session["User"] as User;

      DataAccess da = new DataAccess();
      DataTable tbl = da.GetDataTable(
        "getInvestorUsers"
        , new string[] { "@subRole" }
        , new object[] { (sourcePage == SourcePage.LvreoList || sourcePage == SourcePage.LvreoMasterEdit) ? "L" : "S" });

      DropDownList ddl = new DropDownList();
      ddl.ID = "ddlInvestor" + columnName;
      ddl.Width = Unit.Pixel(200);

      ddl.Items.Add(new ListItem("(none)", ""));
      foreach (DataRow dr in tbl.Rows)
      {
        ddl.Items.Add(new ListItem(dr["InvestorName"].ToString(), dr["UserId"].ToString()));
      }
      ddl.DataBinding += new EventHandler(ddl_DataBinding);

      container.Controls.Add(ddl);
    }

    void ddl_DataBinding(object sender, EventArgs e)
    {
      DropDownList ddl = (DropDownList)sender;
      GridEditFormItem container = (GridEditFormItem)ddl.NamingContainer;
      DataRowView drw = container.DataItem as DataRowView;
      if (drw == null) return;

      string val = drw["InvestorId"].ToString();
      if (ddl.Items.FindByValue(val) != null)
      {
        ddl.SelectedValue = val;
      }
    }

    public System.Collections.Specialized.IOrderedDictionary ExtractValues(Control container)
    {
      OrderedDictionary od = new OrderedDictionary();
      od.Add(columnName, ((DropDownList)(((GridEditFormItem)(container)).FindControl("ddlInvestor" + columnName))).SelectedValue);
      return od;
    }
  }
}
